import sys
import os
import random
from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *

class Demo(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        layout = QVBoxLayout()        

        toolBar = QToolBar()
        
        btn = QPushButton('Add')
        btn.clicked.connect(self.OnAddClicked)
        toolBar.addWidget(btn)

        btn = QPushButton('Insert')
        btn.clicked.connect(self.OnInsertClicked)
        toolBar.addWidget(btn)

        btn = QPushButton('Delete')
        btn.clicked.connect(self.OnDeleteClicked)
        toolBar.addWidget(btn)

        toolBar.addWidget(QLabel('Current:'))
        self.combox =QComboBox()
        self.combox.activated.connect(self.ComboxActivated)
        toolBar.addWidget(self.combox)

        layout.addWidget(toolBar)
        self.stackedwidget = QStackedWidget()        
        self.stackedwidget.currentChanged.connect(self.CurrentChanged)        
        layout.addWidget(self.stackedwidget)

        self.setLayout(layout)
    def OnAddClicked(self):
        widget = f'Label{self.stackedwidget.count()}'
        self.stackedwidget.addWidget(QLabel(widget))
        self.combox.addItem(widget)
        self.parent.OnShowMessage(f"Add {widget}")
    def OnInsertClicked(self):
        widget = f'Label{self.stackedwidget.count()}'
        index = self.stackedwidget.currentIndex()
        if index==-1:
            index=0
        self.stackedwidget.insertWidget(index,QLabel(widget))
        self.combox.insertItem(index,widget)
        self.parent.OnShowMessage(f"Insert {widget} at {index}")
    def OnDeleteClicked(self):
        current = self.stackedwidget.currentWidget()
        if current is None:return        
        self.parent.OnShowMessage(f"Delete {current.text()}")
        self.stackedwidget.removeWidget(current)
        item = self.combox.findText(current.text())
        self.combox.removeItem(item)
    def CurrentChanged(self,index):
        current = self.stackedwidget.widget(index)
        self.parent.OnShowMessage(f"Current {current.text()}")        
    def ComboxActivated(self,index):
        self.stackedwidget.setCurrentIndex(index)


def runDemo(parent):
    wigdet =  Demo(parent)
    return wigdet